package com.yuchen.bearrecord.repository;

import com.yuchen.bearrecord.dto.DrugDto;
import com.yuchen.bearrecord.dto.DrugSelectDto;
import com.yuchen.bearrecord.dto.ExpireDrugDto;
import com.yuchen.bearrecord.entity.Drug;
import com.yuchen.bearrecord.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.List;

public interface DrugRepository extends JpaRepository<Drug, Long> {

    Drug findDrugById(Long id);

    List<DrugDto> findDrugsByDrugName(String drugName);

    List<DrugDto> findDrugsByUser(User user);

    List<DrugSelectDto> findAllByUser(User user);

    @Query("SELECT d FROM Drug d WHERE d.user = ?1 and (d.drugName LIKE %?2% OR d.ingredient LIKE %?2% OR d.indication LIKE %?2% OR d.surplus LIKE %?2% OR d.specification LIKE %?2% OR d.usageDosage LIKE %?2% OR d.place LIKE %?2%)")
    List<Drug> findDrugsByKeyword(User user, String keyword);

    @Query("SELECT new com.yuchen.bearrecord.dto.ExpireDrugDto(d) FROM Drug d WHERE d.user = :user AND d.expireDate < :today")
    List<ExpireDrugDto> findExpiredDrugs(@Param("user") User user, @Param("today") LocalDate today);

    @Query("SELECT new com.yuchen.bearrecord.dto.ExpireDrugDto(d) FROM Drug d WHERE d.user = :user AND (d.expireDate BETWEEN :today AND :sevenDaysLater)")
    List<ExpireDrugDto> findExpiringDrugs(@Param("user") User user, @Param("today") LocalDate today, @Param("sevenDaysLater") LocalDate sevenDaysLater);

    @Transactional
    void deleteDrugById(Long id);

    @Transactional
    void deleteAllByUser(User user);
}
